package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.domain.PageResult;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRelation(id);
    }

    public void save(Role role, Long[] ids) {
        roleMapper.insert(role);
        //维护中间表 根据传入的权限id数组 插入数据到role_permission
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        //先从role_permission 中间表删除 原有的关系数据
        roleMapper.deleteRelation(role.getId());
        //再维护中间表 根据传入的权限id数组 插入数据到role_permission
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        List<Role> roles = roleMapper.query(qo);
        return new PageInfo<Role>(roles);
    }

}
